<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./jquery-3.6.0.min.js"></script>
</head>

<body>

    <table id="tab">
        <thead>
            <tr>
                <td>序号</td>
                <td>摘要</td>
                <td>金额</td>
                <td>操作</td>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td><input></td>
                <td><input class="price"></td>
                <td><input type="button" id="add" value="增加"></td>
            </tr>
        </tbody>

    </table>
    总金额：<input id="total">
    <script>
        $(function() {
            $("#add").on("click", function() {
                let id = $("tr").length
                let html = `<tr><td>${id}</td><td><input></td><td><input class="price"></td><td><input type="button" id="del" value="删除"></td></tr>`;
                // append()在原内容后追加内容
                $("#tab").append(html);
            })

            $(document).on("blur", ".price", function() {
                // $(".price").on("blur", function() {
                let total = [];
                $(".price").each(function() {
                    let price = $(this).val();
                    // console.log($(".price"));
                    total.push(price);
                })
                var sum = 0;
                if (total.length == 0) {
                    return;
                }
                total.forEach(element => {
                    sum += parseInt(element);
                });
                $("#total").val(sum);
            })

            $(document).on("click", "#del", function() {
                // 移除li节点
                $(this).parent().parent().remove();
                // parents()多级
                // $(this).parents("tr").remove();
                let total = [];
                $(".price").each(function() {
                    let price = $(this).val();
                    // console.log($(".price"));
                    total.push(price);
                })
                var sum = 0;
                if (total.length == 0) {
                    return;
                }
                total.forEach(element => {
                    sum += parseInt(element);
                });
                $("#total").val(sum);
            })
        })
    </script>

</body>

</html>